
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, login } from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  // 从缓存中读取初始值
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) { // 退出登录时，删除token
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  async login(context, data) {
    // context代表上下文，用于操作，第二个参数是传进来的参数
    console.log(data)// 登录页面登录按钮方法中调用调试
    // 调用登录接口，会返回token，我们需要存到state中
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {}) // 设置用户新信息为空
    // 退出登录，权限路由也应重置
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
